package com.manopservice.controller;

import java.util.HashMap;
import java.util.Map;

import com.manopservice.model.CarType;
import com.manopservice.service.CarTypeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/carTypes")
public class CarTypeController {

	@Autowired
	private CarTypeService carTypeService;
	
	@RequestMapping(value = "/ShowCarTypes", method = RequestMethod.POST)
	public ModelAndView showCarPart() {
		
		return listCarTypes();
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView saveCarType(@ModelAttribute("carType") CarType  carType,
			BindingResult result) {
		carTypeService.saveCarType(carType);
		return new ModelAndView("redirect:/carTypes.html");
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public ModelAndView deleteCarType(@ModelAttribute("carType") CarType  carType,
			BindingResult result) {
		carTypeService.deleteCarType(carType.getId());
		return new ModelAndView("redirect:/carTypes.html");
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView listCarTypes() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("carTypes",  carTypeService.listCarTypes());

		return new ModelAndView("carTypesList", model);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView addCarType(@ModelAttribute("carType") CarType carType,
			BindingResult result) {
		return new ModelAndView("addCarType");
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView editCarType(@ModelAttribute("carType") CarType carType,
			BindingResult result) {
		
		CarType ct = carTypeService.findCarTypeById(carType.getId());
		
		carType.setNameEng(ct.getNameEng());
		carType.setNameThai(ct.getNameThai());
		carType.setDetail(ct.getDetail());
		
		return new ModelAndView("editCarType");
	}
}